import 'dart:convert';
import 'dart:math';
import '../models/community.dart';

/// 社区服务类
class CommunityService {
  static final CommunityService _instance = CommunityService._internal();
  factory CommunityService() => _instance;
  CommunityService._internal();

  // 模拟数据存储
  final List<Post> _posts = [];
  final List<Topic> _topics = [];
  final List<Comment> _comments = [];
  final List<CommunityUser> _users = [];
  final List<String> _userLikes = []; // 用户点赞记录
  final List<String> _userFollows = []; // 用户关注记录
  final Map<String, int> _userPoints = {}; // 用户积分

  /// 初始化模拟数据
  void initializeMockData() {
    if (_posts.isNotEmpty) return;

    final now = DateTime.now();
    
    // 初始化用户数据
    _users.addAll([
      CommunityUser(
        id: '1',
        username: '传承者小李',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=young%20Chinese%20person%20learning%20traditional%20crafts&image_size=square',
        bio: '热爱传统文化，正在学习剪纸艺术',
        level: 3,
        points: 1250,
        joinDate: now.subtract(const Duration(days: 180)),
        postCount: 25,
        followCount: 156,
        fanCount: 89,
        badges: ['新手上路', '积极发言'],
        isVerified: false,
        isFollowing: false,
      ),
      CommunityUser(
        id: '2',
        username: '书法大师王',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=elderly%20Chinese%20calligraphy%20master&image_size=square',
        bio: '书法爱好者，愿与大家分享书法心得',
        level: 8,
        points: 5680,
        joinDate: now.subtract(const Duration(days: 365)),
        postCount: 128,
        followCount: 892,
        fanCount: 45,
        badges: ['资深用户', '优质内容', '书法达人'],
        isVerified: true,
        isFollowing: false,
      ),
      CommunityUser(
        id: '3',
        username: '茶艺小仙女',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=young%20woman%20practicing%20tea%20ceremony&image_size=square',
        bio: '茶艺师，分享茶文化知识',
        level: 5,
        points: 2890,
        joinDate: now.subtract(const Duration(days: 240)),
        postCount: 67,
        followCount: 445,
        fanCount: 123,
        badges: ['茶艺专家', '热心助人'],
        isVerified: true,
        isFollowing: false,
      ),
    ]);

    // 初始化话题数据
    _topics.addAll([
      Topic(
        id: '1',
        name: '传统手工艺',
        description: '分享各种传统手工艺的学习心得和作品展示',
        icon: '🎨',
        postCount: 156,
        followCount: 892,
        createdAt: now.subtract(const Duration(days: 200)),
        isHot: true,
      ),
      Topic(
        id: '2',
        name: '书法交流',
        description: '书法爱好者的交流园地',
        icon: '✍️',
        postCount: 234,
        followCount: 1245,
        createdAt: now.subtract(const Duration(days: 300)),
        isHot: true,
      ),
      Topic(
        id: '3',
        name: '茶文化',
        description: '探讨茶文化的博大精深',
        icon: '🍵',
        postCount: 89,
        followCount: 567,
        createdAt: now.subtract(const Duration(days: 150)),
        isHot: false,
      ),
      Topic(
        id: '4',
        name: '民俗节日',
        description: '传统节日习俗分享',
        icon: '🏮',
        postCount: 67,
        followCount: 423,
        createdAt: now.subtract(const Duration(days: 120)),
        isHot: false,
      ),
    ]);

    // 初始化评论数据
    _comments.addAll([
      Comment(
        id: '1',
        postId: '1',
        author: _users[1],
        content: '写得很好！剪纸确实需要耐心和技巧，继续加油！',
        createdAt: now.subtract(const Duration(hours: 2)),
        likeCount: 12,
        replyCount: 3,
        parentId: null,
      ),
      Comment(
        id: '2',
        postId: '1',
        author: _users[2],
        content: '我也在学剪纸，可以交流一下经验吗？',
        createdAt: now.subtract(const Duration(hours: 1)),
        likeCount: 5,
        replyCount: 1,
        parentId: null,
      ),
      Comment(
        id: '3',
        postId: '2',
        author: _users[0],
        content: '书法练习确实要持之以恒，感谢分享！',
        createdAt: now.subtract(const Duration(minutes: 30)),
        likeCount: 8,
        replyCount: 0,
        parentId: null,
      ),
    ]);

    // 初始化帖子数据
    _posts.addAll([
      Post(
        id: '1',
        title: '我的剪纸学习心得分享',
        content: '学习剪纸已经三个月了，从最初的笨手笨脚到现在能够剪出一些简单的图案，真的很有成就感。今天想和大家分享一下我的学习心得：\n\n1. 选择合适的工具很重要，一把好的剪刀能让你事半功倍\n2. 从简单的图案开始练习，不要急于求成\n3. 多观察传统剪纸作品，学习其中的技法和构图\n4. 保持耐心，剪纸是一个需要静心的艺术\n\n希望对初学者有帮助！',
        author: _users[0],
        type: PostType.discussion,
        status: PostStatus.published,
        topicId: '1',
        images: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20Chinese%20paper%20cutting%20artwork%20flowers&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=paper%20cutting%20tools%20scissors%20and%20paper&image_size=square',
        ],
        tags: ['剪纸', '学习心得', '新手指南'],
        createdAt: now.subtract(const Duration(hours: 6)),
        updatedAt: now.subtract(const Duration(hours: 6)),
        viewCount: 234,
        likeCount: 45,
        commentCount: 12,
        shareCount: 8,
        isSticky: false,
        isHot: true,
        isPinned: false,
      ),
      Post(
        id: '2',
        title: '书法练习的几个要点',
        content: '作为一个书法爱好者，我想分享一些练习书法的心得：\n\n**基础很重要**\n- 正确的握笔姿势\n- 标准的坐姿\n- 基本笔画的练习\n\n**选择合适的字帖**\n- 初学者建议从楷书开始\n- 选择名家字帖临摹\n- 循序渐进，不要贪多\n\n**持之以恒**\n- 每天坚持练习\n- 记录自己的进步\n- 多与同好交流\n\n希望大家都能在书法的道路上有所收获！',
        author: _users[1],
        type: PostType.tutorial,
        status: PostStatus.published,
        topicId: '2',
        images: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Chinese%20calligraphy%20practice%20with%20brush%20and%20ink&image_size=landscape_4_3',
        ],
        tags: ['书法', '练习方法', '教程'],
        createdAt: now.subtract(const Duration(hours: 12)),
        updatedAt: now.subtract(const Duration(hours: 12)),
        viewCount: 567,
        likeCount: 89,
        commentCount: 23,
        shareCount: 15,
        isSticky: true,
        isHot: true,
        isPinned: true,
      ),
      Post(
        id: '3',
        title: '春节剪纸作品展示',
        content: '马上就要过年了，我剪了一些春节主题的剪纸作品，有福字、窗花、生肖等。虽然技艺还不够精湛，但是满满的年味！大家觉得怎么样？',
        author: _users[0],
        type: PostType.showcase,
        status: PostStatus.published,
        topicId: '1',
        images: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Chinese%20New%20Year%20paper%20cutting%20decorations&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20Chinese%20zodiac%20paper%20cutting&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Chinese%20window%20paper%20cutting%20patterns&image_size=square',
        ],
        tags: ['剪纸', '春节', '作品展示'],
        createdAt: now.subtract(const Duration(days: 1)),
        updatedAt: now.subtract(const Duration(days: 1)),
        viewCount: 189,
        likeCount: 67,
        commentCount: 18,
        shareCount: 12,
        isSticky: false,
        isHot: false,
        isPinned: false,
      ),
      Post(
        id: '4',
        title: '茶艺表演视频分享',
        content: '昨天参加了一个茶艺表演活动，学到了很多新的泡茶技巧。特别是功夫茶的冲泡方法，真的是一门艺术！分享给大家，希望对茶艺爱好者有帮助。',
        author: _users[2],
        type: PostType.video,
        status: PostStatus.published,
        topicId: '3',
        images: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20Chinese%20tea%20ceremony%20performance&image_size=landscape_4_3',
        ],
        tags: ['茶艺', '表演', '技巧分享'],
        createdAt: now.subtract(const Duration(hours: 18)),
        updatedAt: now.subtract(const Duration(hours: 18)),
        viewCount: 345,
        likeCount: 78,
        commentCount: 15,
        shareCount: 9,
        isSticky: false,
        isHot: true,
        isPinned: false,
      ),
    ]);

    // 初始化用户积分
    for (final user in _users) {
      _userPoints[user.id] = user.points;
    }
  }

  /// 获取所有帖子
  Future<List<Post>> getAllPosts() async {
    await Future.delayed(const Duration(milliseconds: 500));
    return List.from(_posts)..sort((a, b) => b.createdAt.compareTo(a.createdAt));
  }

  /// 根据筛选条件获取帖子
  Future<List<Post>> getPostsByFilter(CommunityFilter filter) async {
    await Future.delayed(const Duration(milliseconds: 300));
    
    List<Post> filteredPosts;
    switch (filter) {
      case CommunityFilter.all:
        filteredPosts = List.from(_posts);
        break;
      case CommunityFilter.hot:
        filteredPosts = _posts.where((p) => p.isHot).toList();
        break;
      case CommunityFilter.latest:
        filteredPosts = List.from(_posts);
        break;
      case CommunityFilter.discussion:
        filteredPosts = _posts.where((p) => p.type == PostType.discussion).toList();
        break;
      case CommunityFilter.following:
        // 获取关注用户的帖子
        filteredPosts = _posts.where((p) => _userFollows.contains('${p.author.id}')).toList();
        break;
      case CommunityFilter.sharing:
        filteredPosts = _posts.where((p) => p.type == PostType.sharing).toList();
        break;
      case CommunityFilter.showcase:
        filteredPosts = _posts.where((p) => p.type == PostType.showcase).toList();
        break;
      case CommunityFilter.question:
        filteredPosts = _posts.where((p) => p.type == PostType.question).toList();
        break;
      case CommunityFilter.news:
        filteredPosts = _posts.where((p) => p.type == PostType.news).toList();
        break;
      case CommunityFilter.event:
        filteredPosts = _posts.where((p) => p.type == PostType.event).toList();
        break;
    }
    
    // 排序：置顶帖子在前，然后按时间排序
    filteredPosts.sort((a, b) {
      if (a.isPinned && !b.isPinned) return -1;
      if (!a.isPinned && b.isPinned) return 1;
      if (a.isSticky && !b.isSticky) return -1;
      if (!a.isSticky && b.isSticky) return 1;
      return b.createdAt.compareTo(a.createdAt);
    });
    
    return filteredPosts;
  }

  /// 根据话题获取帖子
  Future<List<Post>> getPostsByTopic(String topicId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    return _posts.where((p) => p.topicId == topicId).toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
  }

  /// 获取热门帖子
  Future<List<Post>> getHotPosts({int limit = 10}) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final hotPosts = List.from(_posts)
      ..sort((a, b) => (b.likeCount + b.commentCount * 2 + b.viewCount * 0.1)
          .compareTo(a.likeCount + a.commentCount * 2 + a.viewCount * 0.1));
    return hotPosts.take(limit).toList();
  }

  /// 根据ID获取帖子详情
  Future<Post?> getPostById(String id) async {
    await Future.delayed(const Duration(milliseconds: 200));
    try {
      final post = _posts.firstWhere((p) => p.id == id);
      // 增加浏览量
      final index = _posts.indexWhere((p) => p.id == id);
      if (index != -1) {
        _posts[index] = _posts[index].copyWith(
          viewCount: _posts[index].viewCount + 1,
        );
      }
      return post;
    } catch (e) {
      return null;
    }
  }

  /// 搜索帖子
  Future<List<Post>> searchPosts(String query) async {
    await Future.delayed(const Duration(milliseconds: 400));
    if (query.isEmpty) return [];
    
    final lowerQuery = query.toLowerCase();
    return _posts.where((post) {
      return post.title.toLowerCase().contains(lowerQuery) ||
             post.content.toLowerCase().contains(lowerQuery) ||
             post.tags.any((tag) => tag.toLowerCase().contains(lowerQuery)) ||
             post.author.username.toLowerCase().contains(lowerQuery);
    }).toList();
  }

  /// 发布帖子
  Future<bool> createPost({
    required String title,
    required String content,
    required String authorId,
    required PostType type,
    required String topicId,
    List<String> images = const [],
    List<String> tags = const [],
  }) async {
    await Future.delayed(const Duration(milliseconds: 500));
    
    final author = _users.firstWhere((u) => u.id == authorId, orElse: () => _users[0]);
    final newPost = Post(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      title: title,
      content: content,
      author: author,
      type: type,
      status: PostStatus.published,
      topicId: topicId,
      images: images,
      tags: tags,
      createdAt: DateTime.now(),
      updatedAt: DateTime.now(),
      viewCount: 0,
      likeCount: 0,
      commentCount: 0,
      shareCount: 0,
      isSticky: false,
      isHot: false,
      isPinned: false,
    );
    
    _posts.insert(0, newPost);
    
    // 更新用户帖子数量和积分
    final userIndex = _users.indexWhere((u) => u.id == authorId);
    if (userIndex != -1) {
      _users[userIndex] = _users[userIndex].copyWith(
        postCount: _users[userIndex].postCount + 1,
        points: _users[userIndex].points + 10, // 发帖奖励10积分
      );
      _userPoints[authorId] = (_userPoints[authorId] ?? 0) + 10;
    }
    
    // 更新话题帖子数量
    final topicIndex = _topics.indexWhere((t) => t.id == topicId);
    if (topicIndex != -1) {
      _topics[topicIndex] = _topics[topicIndex].copyWith(
        postCount: _topics[topicIndex].postCount + 1,
      );
    }
    
    return true;
  }

  /// 点赞帖子
  Future<bool> likePost(String postId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final likeKey = '${userId}_$postId';
    if (!_userLikes.contains(likeKey)) {
      _userLikes.add(likeKey);
      
      // 更新帖子点赞数
      final index = _posts.indexWhere((p) => p.id == postId);
      if (index != -1) {
        _posts[index] = _posts[index].copyWith(
          likeCount: _posts[index].likeCount + 1,
        );
        
        // 给帖子作者增加积分
        final authorId = _posts[index].author.id;
        _userPoints[authorId] = (_userPoints[authorId] ?? 0) + 2;
        
        return true;
      }
    }
    return false;
  }

  /// 取消点赞
  Future<bool> unlikePost(String postId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final likeKey = '${userId}_$postId';
    if (_userLikes.remove(likeKey)) {
      // 更新帖子点赞数
      final index = _posts.indexWhere((p) => p.id == postId);
      if (index != -1) {
        _posts[index] = _posts[index].copyWith(
          likeCount: _posts[index].likeCount - 1,
        );
        
        // 减少帖子作者积分
        final authorId = _posts[index].author.id;
        _userPoints[authorId] = (_userPoints[authorId] ?? 0) - 2;
        
        return true;
      }
    }
    return false;
  }

  /// 检查用户是否已点赞
  Future<bool> isPostLiked(String postId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 100));
    final likeKey = '${userId}_$postId';
    return _userLikes.contains(likeKey);
  }

  /// 获取帖子评论
  Future<List<Comment>> getPostComments(String postId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    return _comments.where((c) => c.postId == postId && c.parentId == null).toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
  }

  /// 获取评论回复
  Future<List<Comment>> getCommentReplies(String commentId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    return _comments.where((c) => c.parentId == commentId).toList()
      ..sort((a, b) => a.createdAt.compareTo(b.createdAt));
  }

  /// 添加评论
  Future<bool> addComment({
    required String postId,
    required String authorId,
    required String content,
    String? parentId,
  }) async {
    await Future.delayed(const Duration(milliseconds: 300));
    
    final author = _users.firstWhere((u) => u.id == authorId, orElse: () => _users[0]);
    final newComment = Comment(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      postId: postId,
      author: author,
      content: content,
      createdAt: DateTime.now(),
      likeCount: 0,
      replyCount: 0,
      parentId: parentId,
    );
    
    _comments.add(newComment);
    
    // 更新帖子评论数
    final postIndex = _posts.indexWhere((p) => p.id == postId);
    if (postIndex != -1) {
      _posts[postIndex] = _posts[postIndex].copyWith(
        commentCount: _posts[postIndex].commentCount + 1,
      );
    }
    
    // 如果是回复，更新父评论的回复数
    if (parentId != null) {
      final parentIndex = _comments.indexWhere((c) => c.id == parentId);
      if (parentIndex != -1) {
        _comments[parentIndex] = _comments[parentIndex].copyWith(
          replyCount: _comments[parentIndex].replyCount + 1,
        );
      }
    }
    
    // 给用户增加积分
    _userPoints[authorId] = (_userPoints[authorId] ?? 0) + 5;
    
    return true;
  }

  /// 获取所有话题
  Future<List<Topic>> getAllTopics() async {
    await Future.delayed(const Duration(milliseconds: 300));
    return List.from(_topics)..sort((a, b) => b.postCount.compareTo(a.postCount));
  }

  /// 获取热门话题
  Future<List<Topic>> getHotTopics({int limit = 5}) async {
    await Future.delayed(const Duration(milliseconds: 200));
    return _topics.where((t) => t.isHot).take(limit).toList();
  }

  /// 根据ID获取话题详情
  Future<Topic?> getTopicById(String id) async {
    await Future.delayed(const Duration(milliseconds: 200));
    try {
      return _topics.firstWhere((t) => t.id == id);
    } catch (e) {
      return null;
    }
  }

  /// 关注话题
  Future<bool> followTopic(String topicId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final followKey = '${userId}_topic_$topicId';
    if (!_userFollows.contains(followKey)) {
      _userFollows.add(followKey);
      
      // 更新话题关注数
      final index = _topics.indexWhere((t) => t.id == topicId);
      if (index != -1) {
        _topics[index] = _topics[index].copyWith(
          followerCount: _topics[index].followerCount + 1,
        );
      }
      
      return true;
    }
    return false;
  }

  /// 取消关注话题
  Future<bool> unfollowTopic(String topicId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final followKey = '${userId}_topic_$topicId';
    if (_userFollows.remove(followKey)) {
      // 更新话题关注数
      final index = _topics.indexWhere((t) => t.id == topicId);
      if (index != -1) {
        _topics[index] = _topics[index].copyWith(
          followerCount: _topics[index].followerCount - 1,
        );
      }
      return true;
    }
    return false;
  }

  /// 检查用户是否已关注话题
  Future<bool> isTopicFollowed(String topicId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 100));
    final followKey = '${userId}_topic_$topicId';
    return _userFollows.contains(followKey);
  }

  /// 获取用户信息
  Future<CommunityUser?> getUserById(String id) async {
    await Future.delayed(const Duration(milliseconds: 200));
    try {
      return _users.firstWhere((u) => u.id == id);
    } catch (e) {
      return null;
    }
  }

  /// 获取用户发布的帖子
  Future<List<Post>> getUserPosts(String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    return _posts.where((p) => p.author.id == userId).toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
  }

  /// 获取用户点赞的帖子
  Future<List<Post>> getUserLikedPosts(String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final likedPostIds = _userLikes
        .where((key) => key.startsWith('${userId}_'))
        .map((key) => key.split('_')[1])
        .toList();
    
    return _posts.where((p) => likedPostIds.contains(p.id)).toList();
  }

  /// 获取用户关注的话题
  Future<List<Topic>> getUserFollowedTopics(String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final followedTopicIds = _userFollows
        .where((key) => key.startsWith('${userId}_topic_'))
        .map((key) => key.split('_')[2])
        .toList();
    
    return _topics.where((t) => followedTopicIds.contains(t.id)).toList();
  }

  /// 关注用户
  Future<bool> followUser(String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final followKey = 'current_user_$userId';
    if (!_userFollows.contains(followKey)) {
      _userFollows.add(followKey);
      
      // 更新用户粉丝数
      final index = _users.indexWhere((u) => u.id == userId);
      if (index != -1) {
        _users[index] = _users[index].copyWith(
          fanCount: _users[index].fanCount + 1,
        );
      }
      
      return true;
    }
    return false;
  }

  /// 取消关注用户
  Future<bool> unfollowUser(String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final followKey = 'current_user_$userId';
    if (_userFollows.remove(followKey)) {
      // 更新用户粉丝数
      final index = _users.indexWhere((u) => u.id == userId);
      if (index != -1) {
        _users[index] = _users[index].copyWith(
          fanCount: _users[index].fanCount - 1,
        );
      }
      return true;
    }
    return false;
  }

  /// 检查用户是否已关注
  Future<bool> isUserFollowed(String userId) async {
    await Future.delayed(const Duration(milliseconds: 100));
    final followKey = 'current_user_$userId';
    return _userFollows.contains(followKey);
  }

  /// 获取用户积分
  Future<int> getUserPoints(String userId) async {
    await Future.delayed(const Duration(milliseconds: 100));
    return _userPoints[userId] ?? 0;
  }

  /// 获取社区统计信息
  Future<Map<String, int>> getCommunityStats() async {
    await Future.delayed(const Duration(milliseconds: 200));
    return {
      'totalPosts': _posts.length,
      'totalUsers': _users.length,
      'totalTopics': _topics.length,
      'totalComments': _comments.length,
      'hotPosts': _posts.where((p) => p.isHot).length,
      'stickyPosts': _posts.where((p) => p.isSticky).length,
    };
  }

  /// 获取帖子类型统计
  Future<Map<String, int>> getPostTypeStats() async {
    await Future.delayed(const Duration(milliseconds: 200));
    final Map<String, int> stats = {};
    for (final post in _posts) {
      final typeText = post.typeText;
      stats[typeText] = (stats[typeText] ?? 0) + 1;
    }
    return stats;
  }

  /// 点赞评论
  Future<bool> likeComment(String commentId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final likeKey = '${userId}_comment_$commentId';
    if (!_userLikes.contains(likeKey)) {
      _userLikes.add(likeKey);
      
      // 更新评论点赞数
      final index = _comments.indexWhere((c) => c.id == commentId);
      if (index != -1) {
        _comments[index] = _comments[index].copyWith(
          likeCount: _comments[index].likeCount + 1,
        );
      }
      
      return true;
    }
    return false;
  }

  /// 取消点赞评论
  Future<bool> unlikeComment(String commentId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final likeKey = '${userId}_comment_$commentId';
    if (_userLikes.remove(likeKey)) {
      // 更新评论点赞数
      final index = _comments.indexWhere((c) => c.id == commentId);
      if (index != -1) {
        _comments[index] = _comments[index].copyWith(
          likeCount: _comments[index].likeCount - 1,
        );
      }
      return true;
    }
    return false;
  }

  /// 收藏帖子
  Future<bool> bookmarkPost(String postId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final bookmarkKey = 'current_user_bookmark_$postId';
    if (!_userLikes.contains(bookmarkKey)) {
      _userLikes.add(bookmarkKey);
      return true;
    }
    return false;
  }

  /// 取消收藏帖子
  Future<bool> unbookmarkPost(String postId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final bookmarkKey = 'current_user_bookmark_$postId';
    return _userLikes.remove(bookmarkKey);
  }

  /// 创建评论
  Future<Comment?> createComment({
    required String postId,
    required String content,
    String? parentId,
  }) async {
    await Future.delayed(const Duration(milliseconds: 300));
    
    final comment = Comment(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      postId: postId,
      author: _users.first, // 使用第一个用户作为当前用户
      content: content,
      createdAt: DateTime.now(),
      likeCount: 0,
      replyCount: 0,
      parentId: parentId,
    );
    
    _comments.add(comment);
    
    // 更新帖子评论数
    final postIndex = _posts.indexWhere((p) => p.id == postId);
    if (postIndex != -1) {
      _posts[postIndex] = _posts[postIndex].copyWith(
        commentCount: _posts[postIndex].commentCount + 1,
      );
    }
    
    return comment;
  }

  /// 清除所有数据（用于测试）
  void clearAllData() {
    _posts.clear();
    _topics.clear();
    _comments.clear();
    _users.clear();
    _userLikes.clear();
    _userFollows.clear();
    _userPoints.clear();
  }
}